package com.dengyuanke.upms.logic.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dengyuanke.common.core.constant.CommonConstants;
import com.dengyuanke.common.core.result.R;
import com.dengyuanke.upms.domain.dto.TreeNode;
import com.dengyuanke.upms.domain.entity.Menu;
import com.dengyuanke.upms.domain.entity.RoleMenu;
import com.dengyuanke.upms.domain.entity.UserRole;
import com.dengyuanke.upms.logic.mapper.MenuMapper;
import com.dengyuanke.upms.logic.mapper.RoleMenuMapper;
import com.dengyuanke.upms.logic.service.IMenuService;
import com.dengyuanke.upms.logic.service.IRoleMenuService;
import com.dengyuanke.upms.logic.service.IRoleService;
import com.dengyuanke.upms.logic.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author dengyuanke
 * @since 2019-06-29
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private IRoleMenuService roleMenuService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public List<TreeNode> findMenusByUserId(String userId) {
        List<UserRole> list = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));

        return null;
    }

    @Override
    public List<Menu> findMenuByRoleId(Long roleId) {
        List<Long> menuIds = roleMenuService.list(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId))
                .stream()
                .map(RoleMenu::getMenuId)
                .collect(Collectors.toList());
        List<Menu> menus = this.list(new LambdaQueryWrapper<Menu>().in(Menu::getId, menuIds).eq(Menu::getDelFlag,0).eq(Menu::getType,CommonConstants.MENU)
                .orderByDesc(Menu::getSort));
        return menus;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R removeMenuById(Integer id) {
        // 查询父节点为当前节点的节点
        List<Menu> menuList = this.list(Wrappers.<Menu>query()
                .lambda().eq(Menu::getParentId, id));
        if (CollUtil.isNotEmpty(menuList)) {
            return R.fail("菜单含有下级不能删除");
        }

        roleMenuService.remove(Wrappers.<RoleMenu>query()
                        .lambda().eq(RoleMenu::getMenuId, id));

        //删除当前菜单及其子菜单
        return R.success(this.removeById(id));
    }
}
